package com.tttshaoqi.server.controller;

import com.tttshaoqi.common.result.PageResult;
import com.tttshaoqi.common.result.Result;
import com.tttshaoqi.common.utils.EmpHolder;
import com.tttshaoqi.pojo.dto.EmployeeDTO;
import com.tttshaoqi.server.mapper.LikeMapper;
import com.tttshaoqi.server.mapper.PostMapper;
import com.tttshaoqi.server.mapper.UserMapper;
import com.tttshaoqi.pojo.entity.Post;
import com.tttshaoqi.pojo.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserExtendController {

    private final UserMapper userMapper;
    private final PostMapper postMapper;
    private final LikeMapper likeMapper;

    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable Long id){
        User u = userMapper.findById(id);
        return u == null ? Result.error("用户不存在") : Result.success(u);
    }

    @GetMapping("/posts")
    public Result<PageResult> myPosts(@RequestParam(defaultValue = "1") int page,
                                      @RequestParam(defaultValue = "12") int size){
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        int p = Math.max(page-1, 0); int s = Math.max(size, 1);
        List<Post> list = postMapper.listByUserId(emp.getId(), p*s, s);
        long total = postMapper.countByUserId(emp.getId());
        return Result.success(new PageResult(total, list));
    }

    @GetMapping("/likes")
    public Result<PageResult> myLikes(@RequestParam(defaultValue = "1") int page,
                                      @RequestParam(defaultValue = "12") int size){
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        int p = Math.max(page-1, 0); int s = Math.max(size, 1);
        List<Long> ids = likeMapper.listPostIdsByUser(emp.getId(), p*s, s);
        List<Post> list = new ArrayList<>();
        for (Long id : ids){
            Post pe = postMapper.findById(id);
            if (pe != null) list.add(pe);
        }
        long total = likeMapper.countByUser(emp.getId());
        return Result.success(new PageResult(total, list));
    }
}


